//
//  Tool.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/5.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class Tool: NSObject {

    class func topViewController() -> UIViewController {
        var resultVC: UIViewController!
        resultVC = Tool()._topViewController(UIApplication.shared.delegate!.window!!.rootViewController!)
        while (resultVC.presentedViewController != nil) {
            resultVC = Tool()._topViewController(resultVC.presentedViewController!)
        }
        return resultVC
    }
    
    fileprivate func _topViewController(_ vc: UIViewController) -> UIViewController {
        if let nav = vc as? UINavigationController {
            return self._topViewController(nav.topViewController!)
        }
        else if let tab = vc as? UITabBarController {
            return self._topViewController(tab.selectedViewController!)
        }
        else {
            return vc
        }
    }
    //MARK: ***正则校验***
    

    //是否是手机号
    class func isValidatePhoneNum(_ number: String) -> Bool {
        if number.characters.count != 11 {
            return false
        }
        let pattern = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.matches(in: number, options: [], range: NSRange.init(location: 0, length: number.characters.count))
        
        if result.count > 0 {
            return true
        }
        
        return false
    }
    
    //是否是合法身份证
    class func checkIsIdentityCard(_ identityCard: String) -> Bool {
        //判断是否为空
        if identityCard.characters.count <= 0 {
            return false
        }
        //判断是否是18位，末尾是否是x
        let regex2: String = "^(\\d{14}|\\d{17})(\\d|[xX])$"
        let identityCardPredicate = NSPredicate(format: "SELF MATCHES %@", regex2)
        if !identityCardPredicate.evaluate(with: identityCard) {
            return false
        }
        //判断生日是否合法
        let range = NSRange(location: 6, length: 8)
        let datestr: String = (identityCard as NSString).substring(with: range)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMdd"
        if formatter.date(from: datestr) == nil {
            return false
        }
        //判断校验位
        if  identityCard.characters.count == 18 {
            let idCardWi: [String] = ["7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"]
            //将前17位加权因子保存在数组里
            let idCardY: [String] = ["1", "0", "10", "9", "8", "7", "6", "5", "4", "3", "2"]
            //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            var idCardWiSum: Int = 0
            //用来保存前17位各自乖以加权因子后的总和
            for i in 0..<17 {
                idCardWiSum += Int((identityCard as NSString).substring(with: NSRange(location: i, length: 1)))! * Int(idCardWi[i])!
            }
            let idCardMod: Int = idCardWiSum % 11
            //计算出校验码所在数组的位置
            let idCardLast: String = identityCard.substring(from: identityCard.index(identityCard.endIndex, offsetBy: -1))
            //得到最后一位身份证号码
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if idCardMod == 2 {
                if idCardLast == "X"{
                    return true
                } else {
                    return false
                }
            } else {
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if (idCardLast as NSString).integerValue == Int(idCardY[idCardMod]) {
                    return true
                } else {
                    return false
                }
            }
        }
        return false
    }

    
    /*********格式转换**********/
    
    //将date转为HH:mm格式的字符串
    class func dateToStringWithHHMMFormat(date: Date) -> String{
        let format = DateFormatter()
        format.dateFormat = "HH:mm"
        let dateString = format.string(from: date)
        return dateString
    }
    
    /*数字转金钱格式
     
     返回格式：
     100 -> 100.00
     1234 -> 1,234.00
     34123.542 -> 34,123.54
     */
    class func numberToMoney(_ numberString: String) -> String? {
        guard let doubleNumber = Double(numberString) else {
            
            return nil
        }
        let numberFormatter = NumberFormatter()
        numberFormatter.positiveFormat = "###,##0.00"
        let formatterString = numberFormatter.string(from: NSNumber.init(value: doubleNumber))
        
        return formatterString
    }
    
    //MARK:用*显示手机号的中间几位
    //如18758361234 -> 187****1234
    class func securityPhoneNumber(_ phoneNumber: String) -> String {
        let startIndex = phoneNumber.index(phoneNumber.startIndex, offsetBy: 3)//获取字符串第4个字符的index
        let lengtIndex = phoneNumber.index(startIndex, offsetBy: 4)//获取字符串第8个字符串的index
        let result = phoneNumber.replacingCharacters(in: startIndex..<lengtIndex, with: "****")//将4-8字符串替换
        return result
    }
    //显示身份证
    // 如421122199111223535
    class func securityWithIDCard(_ idCard: String) -> String {
        if idCard.count < 18{
            return idCard
        }
        let startIndex = idCard.index(idCard.startIndex, offsetBy: 6)//获取字符串第4个字符的index
        let lengtIndex = idCard.index(startIndex, offsetBy: 8)//获取字符串第8个字符串的index
        let result = idCard.replacingCharacters(in: startIndex..<lengtIndex, with: "********")//将4-8字符串替换
        return result
    }
    
    
    
    
    
    /******************百度地图*********************/
    class func calculateDistance(a: CLLocationCoordinate2D, b: CLLocationCoordinate2D) -> CLLocationDistance {
        let point1 = BMKMapPointForCoordinate(a)
        let point2 = BMKMapPointForCoordinate(b)
        let distance = BMKMetersBetweenMapPoints(point1, point2)
        
        return distance
    }
    
    //MARK:***缓存处理***
    //计算缓存大小。返回的整形单位是M
    class func fileSizeOfCache() -> Int {
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        var size = 0
        for file in fileArr! {
            // 把文件名拼接到路径中
            let path = cachePath?.appending("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path!)
            // 用元组取出文件大小属性
            for (abc, bcd) in floder {
                // 累加文件大小
                if abc == FileAttributeKey.size {
                    size += bcd as! Int
                }
            }
        }
        let mm = size / 1024 / 1024
        
        return mm
    }
    
    //删除缓存文件
    class func clearCache() {
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        for file in fileArr! {
            let path = cachePath?.appending("/\(file)")
            if FileManager.default.fileExists(atPath: path!) {
                do {
                    try FileManager.default.removeItem(atPath: path!)
                }
                catch {
                    
                }
            }

        }
    }
    
    //MARK: ***时间相关***
    
    //延时执行
    class func execute(_ delay: Int, completion:() -> Void) {
        
    }

    class func showImage(_ image: UIImage) {
        let vc = Tool.topViewController()
        
        let imageView = UIImageView()
        imageView.frame = vc.view.frame
        vc.view.addSubview(imageView)
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
    }
}
